<template>
  <div class="record-table-container">
    <!-- 搜索区域 -->
    <a-row :gutter="16">
      <a-col :span="8">
        <a-input
          v-model="queryReq.questionId"
          placeholder="请输入题号"
          allow-clear
        >
          <template #prefix>
            <icon-search />
          </template>
        </a-input>
      </a-col>
      <a-col :span="8">
        <a-select
          v-model="queryReq.status"
          placeholder="请选择通过结果"
          allow-clear
          :options="statusOptions"
        />
      </a-col>
      <a-col :span="8">
        <a-input
          v-model="queryReq.language"
          placeholder="请输入编程语言"
          allow-clear
        />
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="24" style="text-align: right; margin: 16px 0 24px">
        <a-space>
          <a-button type="primary" class="search-btn" @click="pageData">
            <template #icon>
              <icon-search />
            </template>
            查询
          </a-button>
          <a-button @click="reset">
            <template #icon>
              <icon-refresh />
            </template>
            重置
          </a-button>
        </a-space>
      </a-col>
    </a-row>

    <!-- 表格区域 -->
    <a-table :data="data.recordList" :loading="loading" :pagination="false">
      <template #columns>
        <a-table-column title="提交号" data-index="id" align="center" />
        <a-table-column title="编程语言" data-index="language" align="center" />
        <a-table-column title="结果" align="center">
          <template #cell="{ record }">
            <a-tag
              :color="
                record.status === 2 || record.status === 3 ? 'green' : 'red'
              "
            >
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="内存" align="center">
          <template #cell="{ record }">
            {{
              record.judgeInfo?.memory ? `${record.judgeInfo.memory}KB` : '-'
            }}
          </template>
        </a-table-column>
        <a-table-column title="耗时" align="center">
          <template #cell="{ record }">
            {{ record.judgeInfo?.time ? `${record.judgeInfo.time}ms` : '-' }}
          </template>
        </a-table-column>
        <a-table-column title="判题状态" align="center">
          <template #cell="{ record }">
            {{ record.judgeInfo?.message || '-' }}
          </template>
        </a-table-column>
        <a-table-column title="题目id" data-index="questionId" align="center" />
        <a-table-column title="创建时间" align="center">
          <template #cell="{ record }">
            {{ formatDate(record) }}
          </template>
        </a-table-column>
        <a-table-column title="AI分析报告" align="center">
          <template #cell="{ record }">
            <a-link @click="handleViewReport(record)">
              <icon-file style="color: #2759cd" />
            </a-link>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 独立的分页组件 -->
    <div class="pagination-container">
      <a-pagination
        :total="pagination.total"
        :current="pagination.current"
        :page-size="pagination.pageSize"
        show-total
        show-jumper
        :page-size-options="pagination.pageSizeOptions"
        @change="onPageChange"
        @page-size-change="onPageSizeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import {
  IconSearch,
  IconRefresh,
  IconFile
} from '@arco-design/web-vue/es/icon';
import { useRouter } from 'vue-router';
import { OjProblemSubmitService } from '@/api/gen-api/services/OjProblemSubmitService';
import { useUserStore } from '@/store';
import dayjs from 'dayjs';

const userStore = useUserStore();
const loading = ref(false);
const queryReq = ref({
  language: '',
  questionId: undefined,
  status: undefined,
  code: '',
  codeStatus: undefined
});

const statusOptions = [
  { label: '成功', value: 3 },
  { label: '成功', value: 2 },
  { label: '失败', value: 4 },
  { label: '判题中', value: 1 },
  { label: '待判题', value: 0 }
];

const data = reactive({
  recordList: []
});

const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
});

const router = useRouter();

// 页面变化处理函数
const onPageChange = (page: number) => {
  console.log('页码变化:', page);
  console.log('分页之前的状态:', { ...pagination });

  // 确保是数字类型
  pagination.current = Number(page);

  console.log('分页之后的状态:', { ...pagination });
  pageData();
};

// 每页条数变化处理函数
const onPageSizeChange = (pageSize: number) => {
  console.log('每页条数变化:', pageSize);
  console.log('分页大小变化之前的状态:', { ...pagination });

  // 确保是数字类型
  pagination.pageSize = Number(pageSize);
  pagination.current = 1;

  console.log('分页大小变化之后的状态:', { ...pagination });
  pageData();
};

const getStatusText = (status: number) => {
  const statusMap = {
    0: '待判题',
    1: '判题中',
    2: '成功',
    3: '成功',
    4: '失败'
  };
  return statusMap[status] || '未知';
};

// 打印记录的所有字段名，帮助调试
const logRecordKeys = (record: any) => {
  if (!record) return;
  console.log('记录所有字段名:', Object.keys(record));
  Object.keys(record).forEach(key => {
    console.log(`${key}:`, record[key]);
  });
};

// 格式化日期，优先使用后端返回的createTime，如果没有则从ID解析
const formatDate = (record: any) => {
  if (!record) return '-';

  // 1. 首先检查是否存在createTime字段
  if (record.createTime) {
    return dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss');
  }

  // 2. 如果没有createTime，则尝试从ID解析（作为备选方案）
  try {
    // 雪花ID的时间戳是从2023年1月1日开始的毫秒数，存储在高位41位中
    const idStr = String(record.id);
    const snowflakeTimestamp = BigInt(idStr) >> 22n;
    const epoch = new Date('2023-01-01').getTime();
    const timestamp = Number(snowflakeTimestamp) + epoch;

    if (!isNaN(timestamp)) {
      return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss') + ' (估算)';
    }
  } catch (e) {
    console.error('ID解析时间错误', e, record.id);
  }

  return '-';
};

const pageData = async () => {
  console.log('开始查询数据, 当前分页状态:', { ...pagination });
  loading.value = true;

  try {
    const userId = userStore.id;
    if (!userId) {
      Message.error('请先登录');
      loading.value = false;
      return;
    }

    // 创建Paging实例
    const paging = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    };

    console.log('发送API请求, 参数:', {
      userId,
      paging,
      requestBody: queryReq.value
    });

    // 使用服务调用API
    const response = await OjProblemSubmitService.pageInfoByUserId(
      userId,
      paging,
      queryReq.value
    );

    console.log('API响应:', response);
    console.log('分页数据:', {
      pageNumber: response.result?.pageNumber,
      totalRow: response.result?.totalRow,
      totalPage: response.result?.totalPage
    });

    if (response.code === 200 && response.result) {
      // 记录原始数据记录数
      const recordsCount = response.result.records?.length || 0;
      console.log(`获取到${recordsCount}条记录`);

      // 更新表格数据
      data.recordList = response.result.records || [];

      // 类型转换：确保分页参数是数字类型
      pagination.total = Number(response.result.totalRow) || 0;
      pagination.current = Number(response.result.pageNumber) || 1;

      console.log('数据更新后的分页状态:', { ...pagination });

      // 打印第一条记录的部分字段
      if (data.recordList.length > 0) {
        const firstRecord = data.recordList[0];
        console.log('第一条记录:', {
          id: firstRecord.id,
          status: firstRecord.status,
          language: firstRecord.language,
          createTime: firstRecord.createTime,
          formattedDate: formatDate(firstRecord)
        });

        // 详细打印字段类型和值，便于调试
        console.log('创建时间字段:', {
          value: firstRecord.createTime,
          type: typeof firstRecord.createTime,
          isNull: firstRecord.createTime === null,
          isUndefined: firstRecord.createTime === undefined
        });
      } else {
        console.log('没有查询到记录');
      }
    } else {
      Message.error(response.message || '获取数据失败');
    }
    loading.value = false;
  } catch (error) {
    console.error('获取数据失败:', error);
    Message.error(
      '获取数据失败: ' +
        (error.response?.data?.message || error.message || '未知错误')
    );
    loading.value = false;
  }
};

const reset = () => {
  queryReq.value = {
    language: '',
    questionId: undefined,
    status: undefined,
    code: '',
    codeStatus: undefined
  };
  pagination.current = 1;
  pageData();
};

const handleViewReport = (record: any) => {
  console.log('查看分析报告，记录ID:', record.id, '完整记录:', record);
  
  // 确保id是有效值
  if (!record.id) {
    console.error('提交记录ID无效:', record);
    Message.error('提交记录ID无效');
    return;
  }
  
  // 确保ID以字符串形式传递，避免JS大数精度问题
  const recordId = String(record.id);
  console.log('传递给路由的字符串ID:', recordId);
  
  router.push({
    name: 'ReportDetail',
    params: {
      id: recordId
    }
  });
};

onMounted(() => {
pageData();
});
</script>

<style scoped lang="less">
.record-table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;

  :deep(.arco-btn-primary),
  :deep(.search-btn) {
    background-color: #2759cd !important;
    border-color: #2759cd !important;

    &:hover {
      background-color: #1a3a8f !important;
      border-color: #1a3a8f !important;
    }
  }

  :deep(.arco-table) {
    .arco-table-th {
      background-color: #f2f3f5 !important;
    }
  }

  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
